package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradeSkuOrderBean;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;

public class Dws09_TradeSkuOrderWindow_03 {

    public static void main(String[] args) {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.读取Kafka DWD层下单明细主题数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_trade_order_detail", "sku_order_221109"), WatermarkStrategy.noWatermarks(), "kafka-source");

        //TODO 3.过滤&转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //TODO 4.提取时间戳生成Watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("create_time");
            }
        }));

        //TODO 5.按照订单明细ID分组
        KeyedStream<JSONObject, String> keyedByDetailIdDS = jsonObjWithWMDS.keyBy(json -> json.getString("id"));

        //TODO 6.去重,并转换为JavaBean对象
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderDS = keyedByDetailIdDS.map(new RichMapFunction<JSONObject, TradeSkuOrderBean>() {

            private ValueState<String> leftState;
            private ValueState<String> rightState;

            @Override
            public void open(Configuration parameters) throws Exception {

                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.seconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();

                ValueStateDescriptor<String> leftDesc = new ValueStateDescriptor<>("left", String.class);
                leftDesc.enableTimeToLive(ttlConfig);
                ValueStateDescriptor<String> rightDesc = new ValueStateDescriptor<>("right", String.class);
                rightDesc.enableTimeToLive(ttlConfig);

                leftState = getRuntimeContext().getState(leftDesc);
                rightState = getRuntimeContext().getState(rightDesc);
            }

            @Override
            public TradeSkuOrderBean map(JSONObject value) throws Exception {

                //取出状态
                String left = leftState.value();
                String right = rightState.value();

                BigDecimal oriAmount = new BigDecimal("0.0");
                BigDecimal totalAmount = new BigDecimal("0.0");
                BigDecimal couponAmount = new BigDecimal("0.0");

                if (left == null) { //表示到达的为第一条数据,则保留原值
                    oriAmount = value.getBigDecimal("split_original_amount");
                    totalAmount = value.getBigDecimal("split_total_amount");
                    couponAmount = value.getBigDecimal("split_coupon_amount");
                    leftState.update("1");
                }

                //获取右表累加字段
                BigDecimal splitActivityAmount = value.getBigDecimal("split_activity_amount");

                if (right == null && splitActivityAmount != null) {
                    rightState.update("1");
                } else {
                    splitActivityAmount = new BigDecimal("0.0");
                }

                return TradeSkuOrderBean.builder()
                        .skuId(value.getString("sku_id"))
                        .skuName(value.getString("sku_name"))
                        .originalAmount(oriAmount)
                        .orderAmount(totalAmount)
                        .couponAmount(couponAmount)
                        .activityAmount(splitActivityAmount)
                        .build();
            }
        });

    }

}
